import axios from "axios"
import { Promise } from "core-js";
import ElementUI from "element-ui";
import { serverIp } from "./config";

const request = axios.create({
    baseURL:"http://"+serverIp+":8081",
    timeout:5000
})

//reques请求拦截器
request.interceptors.request.use(config => {
    config.headers['Content-Type']='application/json;charset=utf-8';
    let user=localStorage.getItem("user") ? JSON.parse( localStorage.getItem("user")):null;
    if(user){
    config.headers['token']=user.token;
    }
    return config;
},
   erro => {
       return Promise.reject(erro)
   }
);
//response拦截器
request.interceptors.response.use(response => {
    let res = response.data;
    //返回文件
    if(response.config.responseType=='blob'){
        return res;
    }
    //字符串处理
    if(typeof res == 'string'){
        res = res ? JSON.parse(res) : res;
    }
    //token验证失败给出提示
    if(res.status==401){
         ElementUI.Message({
             message: res.msg,
             type: 'warning'
         })
    }
    return res;
},erro => {
     console.log('erro'+erro);
     return Promise.reject(erro);
}
);

export default request